<template>
  <div class="red-management">
    <!-- 顶部布局 -->
    <div class="top-layout">
      <!-- 集合（样本）管理标题 -->
      <div class="section-title-container">
        <h3 class="section-title" v-if="activeTab === 'collect'">集合管理</h3>
        <h3 class="section-title" v-if="activeTab === 'sample'">样本管理</h3>
      </div>
      <!-- 集合选择器 -->
      <div class="collection-selector" v-if="activeTab === 'sample'">
        <el-select
          v-model="sampleQuery.collectionName"
          placeholder="请选择集合"
          class="collection-select"
          popper-class="collection-select-dropdown"
          @change="loadSamples"
        >
          <el-option
            v-for="col in collections"
            :key="col.collectionName"
            :label="col.collectionName"
            :value="col.collectionName"
          >
            <div class="collection-option">
              <el-icon><FolderOpened /></el-icon>
              <span class="option-label">{{ col.collectionName }}</span>
            </div>
          </el-option>
        </el-select>
      </div>
      <!-- 右侧按钮区域 -->
      <div class="right-buttons">
        <el-button type="danger" @click="showCollectForm" v-if="activeTab === 'collect'">
          <el-icon><CirclePlus /></el-icon>
          新建集合
        </el-button>
        <el-button type="danger" @click="showSampleForm" v-if="activeTab === 'sample'">
          <el-icon><CirclePlus /></el-icon>
          新建样本
        </el-button>
        <div class="button-container">
          <el-button
            :class="{ 'active-button': activeTab === 'collect' }"
            @click="activeTab = 'collect'"
          >
            <el-icon :class="'nav-icon'"><component :is="tabs[0].icon" /></el-icon>
            <span class="nav-text">{{ tabs[0].label }}</span>
          </el-button>
          <el-button
            :class="{ 'active-button': activeTab ==='sample' }"
            @click="activeTab ='sample'"
          >
            <el-icon :class="'nav-icon'"><component :is="tabs[1].icon" /></el-icon>
            <span class="nav-text">{{ tabs[1].label }}</span>
          </el-button>
        </div>
      </div>
    </div>

    <!-- 主内容区 -->
    <main class="management-main">
      <!-- 集合管理 -->
      <section v-show="activeTab === 'collect'" class="collect-section">
        <!-- 集合表格 -->
        <el-table
          :data="collections"
          v-loading="loading.collect"
          class="data-table"
          stripe
          height="calc(100vh - 230px)"
        >
          <el-table-column prop="collectionName" label="集合名称" width="180" />
          <el-table-column prop="collectionComment" label="描述" />
          <el-table-column label="字段配置" width="300">
            <template #default="{ row }">
              <div class="field-tags">
                <el-tag
                  v-for="field in row.sampleColumns"
                  :key="field.name"
                  class="field-tag"
                  effect="plain"
                >
                  {{ field.name }}: {{ field.dataType.toLowerCase() }}
                </el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="{ row }">
              <el-button
                type="danger"
                link
                @click="handleDeleteCollection(row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="collectPagination.current"
            v-model:page-size="collectPagination.size"
            :total="collectPagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleCollectSizeChange"
            @current-change="handleCollectCurrentChange"
          />
        </div>

        <!-- 新建集合弹窗 -->
        <el-dialog
          v-model="showCollectDialog"
          title="新建集合"
          class="collect-dialog"
          width="800px"
        >
          <el-form
            ref="collectFormRef"
            :model="collectForm"
            label-width="110px"
            label-position="left"
          >
            <el-form-item
              label="命名空间"
              prop="namespace"
              :rules="[
                { required: true, message: '请输入命名空间' },
                { pattern: /^[a-z0-9_]{1,12}$/, message: '最大12个字符,支持小写字母、数字和下划线的组合' }
              ]"
            >
              <el-input
                v-model="collectForm.namespace"
                placeholder="最大12个字符,支持小写字母、数字和下划线的组合"
              />
            </el-form-item>

            <el-form-item
              label="集合名称"
              prop="collectionName"
              :rules="[
                { required: true, message: '请输入集合名称' },
                { pattern: /^[a-z0-9_]{1,24}$/, message: '最大24个字符,支持小写字母、数字和下划线的组合' }
              ]"
            >
              <el-input
                v-model="collectForm.collectionName"
                placeholder="最大24个字符,支持小写字母、数字和下划线的组合"
              />
            </el-form-item>

            <el-form-item
              label="存储组件"
              prop="storageEngine"
              :rules="[{ required: true, message: '请选择存储组件' }]"
            >
              <el-select v-model="collectForm.storageEngine" placeholder="保留图片及人脸信息的存储组件">
                <el-option label="CURR_DB" value="CURR_DB" />
              </el-select>
            </el-form-item>

            <el-form-item label="保留信息">
              <el-switch v-model="collectForm.storageFaceInfo" />
              <span class="switch-tip">是否保留图片及人脸信息</span>
            </el-form-item>

            <!-- 人脸属性字段配置 -->
            <div class="field-config">
              <div class="field-group">
                <div class="field-header">
                  <h4>人脸属性</h4>
                  <el-button
                    type="danger"
                    plain
                    size="small"
                    @click="addField('face')"
                  >
                    + 添加字段
                  </el-button>
                </div>
                <div
                  v-for="(field, index) in collectForm.faceColumns"
                  :key="index"
                  class="field-item"
                >
                  <el-input
                    v-model="field.name"
                    placeholder="名称"
                    class="field-name"
                  />
                  <el-select
                    v-model="field.dataType"
                    placeholder="字段类型"
                    class="field-type"
                  >
                    <el-option
                      v-for="type in dataTypes"
                      :key="type"
                      :label="type.toLowerCase()"
                      :value="type"
                    />
                  </el-select>
                  <el-input
                    v-model="field.comment"
                    placeholder="描述"
                    class="field-desc"
                  />
                  <el-button
                    type="danger"
                    text
                    @click="removeField('face', index)"
                  >
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
              </div>
            </div>

            <!-- 样本属性字段配置 -->
            <div class="field-config">
              <div class="field-group">
                <div class="field-header">
                  <h4>样本属性</h4>
                  <el-button
                    type="danger"
                    plain
                    size="small"
                    @click="addField('sample')"
                  >
                    + 添加字段
                  </el-button>
                </div>
                <div
                  v-for="(field, index) in collectForm.sampleColumns"
                  :key="index"
                  class="field-item"
                >
                  <el-input
                    v-model="field.name"
                    placeholder="名称"
                    class="field-name"
                  />
                  <el-select
                    v-model="field.dataType"
                    placeholder="字段类型"
                    class="field-type"
                  >
                    <el-option
                      v-for="type in dataTypes"
                      :key="type"
                      :label="type.toLowerCase()"
                      :value="type"
                    />
                  </el-select>
                  <el-input
                    v-model="field.comment"
                    placeholder="描述"
                    class="field-desc"
                  />
                  <el-button
                    type="danger"
                    text
                    @click="removeField('sample', index)"
                  >
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
              </div>
            </div>

            <el-form-item
              label="集合描述"
              prop="collectionComment"
            >
              <el-input
                v-model="collectForm.collectionComment"
                type="textarea"
                :rows="3"
                placeholder="最大128个字符"
                maxlength="128"
                show-word-limit
              />
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="showCollectDialog = false">取消</el-button>
            <el-button type="danger" @click="submitCollectForm">
              立即创建
            </el-button>
          </template>
        </el-dialog>
      </section>

      <!-- 样本管理 -->
      <section v-show="activeTab ==='sample'" class="sample-section">
        <!-- 样本表格 -->
        <el-table
          :data="samples"
          v-loading="loading.sample"
          class="data-table"
          stripe
          height="calc(100vh - 230px)"
        >
          <el-table-column prop="sampleId" label="样本ID" width="280" />
          <el-table-column label="姓名" width="180">
            <template #default="{ row }">
              {{ getFieldValue(row.sampleData, 'name') }}
            </template>
          </el-table-column>
          <el-table-column label="标签" min-width="200">
            <template #default="{ row }">
              <div class="label-tags">
                <el-tag
                  v-for="field in getFaceLabels(row.sampleData)"
                  :key="field.key"
                  class="label-tag"
                  effect="plain"
                >
                  {{ field.key }}: {{ field.value }}
                </el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" link @click="openAddFaceDialog(row)">
                新增人脸
              </el-button>
              <el-button type="danger" link @click="deleteSample(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.size"
            :total="pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>

        <!-- 新建样本弹窗 -->
        <el-dialog
          v-model="showSampleDialog"
          title="新建样本"
          class="sample-dialog"
          width="800px"
        >
          <el-form
            ref="sampleFormRef"
            :model="sampleForm"
            label-width="120px"
            label-position="left"
          >
            <el-form-item
              label="集合名称"
              prop="collectionName"
              :rules="[{ required: true, message: '请选择集合' }]"
            >
              <el-select
                v-model="sampleForm.collectionName"
                placeholder="请选择集合"
                @change="handleCollectionChange"
              >
                <el-option
                  v-for="col in collections"
                  :key="col.collectionName"
                  :label="col.collectionName"
                  :value="col.collectionName"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="样本编号">
              <el-input v-model="sampleForm.sampleId" disabled>
                <template #prefix>
                  <el-icon><Key /></el-icon>
                </template>
              </el-input>
              <div class="form-tip">系统自动生成的唯一标识</div>
            </el-form-item>

            <!-- 扩展字段 -->
            <div class="field-section">
              <div class="section-header">
                <h4>扩展字段</h4>
                <el-button
                  type="danger"
                  plain
                  size="small"
                  @click="addSampleField('extend')"
                >
                  + 添加字段
                </el-button>
              </div>
              <div
                v-for="(field, index) in sampleForm.sampleData"
                :key="index"
                class="field-item"
              >
                <el-input
                  v-model="field.key"
                  placeholder="名称"
                  class="field-name"
                />
                <el-input
                  v-model="field.value"
                  placeholder="值"
                  class="field-value"
                />
                <el-button
                  type="danger"
                  text
                  @click="removeSampleField('extend', index)"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </div>

            <!-- 照片上传 -->
            <el-form-item
              label="照片上传"
            >
              <el-upload
                ref="uploadRef"
                action=""
                list-type="picture-card"
                :auto-upload="false"
                :limit="20"
                multiple
                accept="image/*"
                :on-change="handleImageChange"
                :on-remove="handleImageRemove"
              >
                <el-icon><Plus /></el-icon>
                <template #tip>
                  <div class="upload-tip">支持多张图片上传，最多20张，每张大小不超过10MB</div>
                </template>
              </el-upload>
            </el-form-item>

            <!-- 人脸字段 -->
            <div class="field-section">
              <div class="section-header">
                <h4>人脸字段</h4>
                <el-button
                  type="danger"
                  plain
                  size="small"
                  @click="addSampleField('face')"
                >
                  + 添加字段
                </el-button>
              </div>
              <div
                v-for="(field, index) in faceForm.faceData"
                :key="index"
                class="field-item"
              >
                <el-input
                  v-model="field.key"
                  placeholder="名称"
                  class="field-name"
                />
                <el-input
                  v-model="field.value"
                  placeholder="值"
                  class="field-value"
                />
                <el-button
                  type="danger"
                  text
                  @click="removeSampleField('face', index)"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </div>

            <!-- 阈值设置 -->
            <el-form-item label="质量分数阈值">
              <div class="slider-container">
                <el-slider
                  v-model="faceForm.faceScoreThreshold"
                  :min="0"
                  :max="100"
                  :step="1"
                  show-input
                  :format-tooltip="formatTooltip"
                />
                <div class="slider-tip">
                  人脸质量分数阈值,范围: [0,100]: 默认0。当设置为0时，会默认使用当前模型的默认值，该方法为推荐使用方式
                </div>
              </div>
            </el-form-item>

            <el-form-item label="相似度最大阈值">
              <div class="slider-container">
                <el-slider
                  v-model="faceForm.maxConfidenceThresholdWithOtherSample"
                  :min="0"
                  :max="100"
                  :step="1"
                  show-input
                  :format-tooltip="formatTooltip"
                />
                <div class="slider-tip">
                  当前样本与其他样本的人脸相似度的最大阈值,范围: [0,100]: 默认0。当设置为0时，表示不做类间相似度判断逻辑,开启后对效率有较大影响
                </div>
              </div>
            </el-form-item>

            <el-form-item label="相似度最小阈值">
              <div class="slider-container">
                <el-slider
                  v-model="faceForm.minConfidenceThresholdWithThisSample"
                  :min="0"
                  :max="100"
                  :step="1"
                  show-input
                  :format-tooltip="formatTooltip"
                />
                <div class="slider-tip">
                  当前样本的人脸相似度的最小阈值,范围: [0,100]: 默认0。当设置为0时，表示不做类间相似度判断逻辑,开启后对效率有较大影响
                </div>
              </div>
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="showSampleDialog = false">取消</el-button>
            <el-button type="danger" @click="submitSampleForm">提交</el-button>
          </template>
        </el-dialog>

        <!-- 新增人脸弹窗 -->
        <el-dialog
          v-model="showAddFaceDialog"
          title="新增人脸"
          class="sample-dialog"
          width="800px"
        >
          <el-form
            ref="addFaceFormRef"
            :model="addFaceForm"
            label-width="120px"
            label-position="left"
          >
            <!-- 照片上传 -->
            <el-form-item
              label="照片上传"
            >
              <el-upload
                ref="addFaceUploadRef"
                action=""
                list-type="picture-card"
                :auto-upload="false"
                :limit="20"
                multiple
                accept="image/*"
                :on-change="handleAddFaceImageChange"
                :on-remove="handleAddFaceImageRemove"
              >
                <el-icon><Plus /></el-icon>
                <template #tip>
                  <div class="upload-tip">支持多张图片上传，最多20张，每张大小不超过10MB</div>
                </template>
              </el-upload>
            </el-form-item>

            <!-- 人脸字段 -->
            <div class="field-section">
              <div class="section-header">
                <h4>人脸字段</h4>
                <el-button
                  type="danger"
                  plain
                  size="small"
                  @click="addFaceField"
                >
                  + 添加字段
                </el-button>
              </div>
              <div
                v-for="(field, index) in addFaceForm.faceData"
                :key="index"
                class="field-item"
              >
                <el-input
                  v-model="field.key"
                  placeholder="名称"
                  class="field-name"
                />
                <el-input
                  v-model="field.value"
                  placeholder="值"
                  class="field-value"
                />
                <el-button
                  type="danger"
                  text
                  @click="removeFaceField(index)"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </div>

            <!-- 阈值设置 -->
            <el-form-item label="质量分数阈值">
              <div class="slider-container">
                <el-slider
                  v-model="addFaceForm.faceScoreThreshold"
                  :min="0"
                  :max="100"
                  :step="1"
                  show-input
                  :format-tooltip="formatTooltip"
                />
                <div class="slider-tip">
                  人脸质量分数阈值,范围: [0,100]: 默认0。当设置为0时，会默认使用当前模型的默认值，该方法为推荐使用方式
                </div>
              </div>
            </el-form-item>

            <el-form-item label="相似度最大阈值">
              <div class="slider-container">
                <el-slider
                  v-model="addFaceForm.maxConfidenceThresholdWithOtherSample"
                  :min="0"
                  :max="100"
                  :step="1"
                  show-input
                  :format-tooltip="formatTooltip"
                />
                <div class="slider-tip">
                  当前样本与其他样本的人脸相似度的最大阈值,范围: [0,100]: 默认0。当设置为0时，表示不做类间相似度判断逻辑,开启后对效率有较大影响
                </div>
              </div>
            </el-form-item>

            <el-form-item label="相似度最小阈值">
              <div class="slider-container">
                <el-slider
                  v-model="addFaceForm.minConfidenceThresholdWithThisSample"
                  :min="0"
                  :max="100"
                  :step="1"
                  show-input
                  :format-tooltip="formatTooltip"
                />
                <div class="slider-tip">
                  当前样本的人脸相似度的最小阈值,范围: [0,100]: 默认0。当设置为0时，表示不做类间相似度判断逻辑,开启后对效率有较大影响
                </div>
              </div>
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="showAddFaceDialog = false">取消</el-button>
            <el-button type="danger" @click="submitAddFaceForm">提交</el-button>
          </template>
        </el-dialog>
      </section>
    </main>
  </div>
</template>

<script setup lang="ts">
import {ref, reactive, computed, onMounted, watch} from 'vue'
import {ElLoading, ElMessage, ElMessageBox} from 'element-plus'
import type { FormInstance } from 'element-plus'
import {
  FolderOpened,
  Delete,
  CirclePlus,
  Collection,
  User,
  Key,
  Plus,
  Search
} from '@element-plus/icons-vue'
import {collectApi, faceApi, sampleApi} from '@/utils/api'
import type {
  CollectReq,
  SampleDataReq,
  SampleDataRepVo,
  DataType, FaceDataReq,
  CollectRepVo
} from '@/utils/types'

// 数据类型枚举
const dataTypes: DataType[] = ['BOOL', 'DOUBLE', 'FLOAT', 'INT', 'STRING']

onMounted(() => {
  loadCollections()
})

// 全局状态
const namespace = ref('namespace_1')
const activeTab = ref<'collect' |'sample'>('collect')

// 集合管理相关
const collections = ref<CollectRepVo[]>([])
const loading = reactive({ collect: false, sample: false })
const showCollectDialog = ref(false)
const collectForm = reactive<CollectReq>({
  namespace: 'namespace_1',
  collectionName: '',
  collectionComment: '',
  storageEngine: 'CURR_DB',
  storageFaceInfo: false,
  faceColumns: [],
  sampleColumns: []
})
const collectFormRef = ref<FormInstance>()

// 集合管理分页
const collectPagination = reactive({
  current: 1,
  size: 20,
  total: 0
})

// 样本管理相关
const samples = ref<SampleDataRepVo[]>([])
const sampleQuery = reactive({
  namespace: 'namespace_1',
  collectionName: '',
  sampleId: '',
  offset: 0,
  limit: 10
})
const pagination = reactive({
  current: 1,
  size: 20,
  total: 0
})
const showSampleDialog = ref(false)

const sampleForm = reactive<SampleDataReq & { images?: File[] }>({
  namespace: 'namespace_1',
  collectionName: '',
  sampleId: '',
  sampleData: [],
  images: []
})

// 人脸集合
const faceImgBase64List = ref<string[]>([])

// 人脸表单数据
const faceForm = reactive<FaceDataReq>({
  collectionName:sampleForm.collectionName,
  faceData:[],
  faceScoreThreshold:0,
  imageBase64:'',
  maxConfidenceThresholdWithOtherSample:0,
  minConfidenceThresholdWithThisSample:0,
  namespace: sampleForm.namespace,
  sampleId: sampleForm.sampleId
})

const sampleFormRef = ref<FormInstance>()

// 计算属性
const currentFields = computed(() => {
  const collection = collections.value.find(
    c => c.collectionName === sampleForm.collectionName
  )
  return collection?.sampleColumns || []
})

// 导航选项卡配置
const tabs = [
  { value: 'collect', label: '集合管理', icon: Collection },
  { value:'sample', label: '样本管理', icon: User }
]

// 加载集合列表
const loadCollections = async () => {
  console.log("加载")
  try {
    loading.collect = true
    const response = await collectApi.list(namespace.value)
    console.log("加载集合",response)
    collections.value = response.data?.data || []
    // 如果有集合，默认选择第一个
    if (collections.value.length > 0) {
      sampleQuery.collectionName = collections.value[0].collectionName
      loadSamples()
    }
  } catch (error) {
    console.error('加载集合失败:', error)
  } finally {
    loading.collect = false
  }
}

// 监听标签页切换
watch(activeTab, (newVal) => {
  if (newVal === 'sample' && collections.value.length > 0 && !sampleQuery.collectionName) {
    sampleQuery.collectionName = collections.value[0].collectionName
    loadSamples()
  }
})

// 提交集合表单
const submitCollectForm = async () => {
  try {
    await collectFormRef.value?.validate()
    await collectApi.create(collectForm)
    ElMessage.success('集合创建成功')
    showCollectDialog.value = false
    await loadCollections()
  } catch (error) {
    console.error('创建集合失败:', error)
  }
}

// 删除集合
const handleDeleteCollection = async (col: CollectReq) => {
  try {
    await ElMessageBox.confirm(`确认删除集合 "${col.collectionName}"?`, '警告', {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
      confirmButtonClass: 'el-button--danger'
    })
    await collectApi.delete({
      namespace: namespace.value,
      collectionName: col.collectionName
    })
    ElMessage.success('删除成功')
    await loadCollections()
  } catch (error) {
    console.log('取消删除')
  }
}

// 动态字段管理
const addField = (type: 'face' | 'sample') => {
  const newField = { name: '', dataType: 'STRING' as DataType, comment: '' }
  if (type === 'face') {
    newField.name = 'label'
    collectForm.faceColumns?.push(newField)
  } else {
    newField.name = 'name'
    collectForm.sampleColumns?.push(newField)
  }
}

const removeField = (type: 'face' | 'sample', index: number) => {
  if (type === 'face') {
    collectForm.faceColumns?.splice(index, 1)
  } else {
    collectForm.sampleColumns?.splice(index, 1)
  }
}

// 样本管理相关方法
const loadSamples = async () => {
  try {
    loading.sample = true
    const params = {
      ...sampleQuery,
      offset: (pagination.current - 1) * pagination.size,
      limit: pagination.size
    }
    const response = await sampleApi.list(params)
    samples.value = response.data?.data || []
    pagination.total = (response.data?.data || []).length // 使用后端返回的数据长度
  } catch (error) {
    console.error('加载样本失败:', error)
  } finally {
    loading.sample = false
  }
}

// 生成样本ID
const generateSampleId = () => {
  const timestamp = Date.now().toString(36).substring(0, 5)  // 5位时间戳
  const randomStr = Math.random().toString(36).substring(2, 9)  // 7位随机字符
  return `fa${timestamp}${randomStr}`
}

const convertToBase64 = (file: File) => {
  return new Promise<string>((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = () => resolve(reader.result as string)
    reader.onerror = reject
    reader.readAsDataURL(file)
  })
}
// 处理集合变化
const handleCollectionChange = () => {
  sampleForm.sampleId = generateSampleId()
  sampleForm.sampleData = []
  faceForm.sampleId = sampleForm.sampleId
  faceForm.collectionName = sampleForm.collectionName
  faceForm.faceData = []
  faceForm.namespace = sampleForm.namespace
}

// 处理图片变化
const handleImageChange = async (file: any) => {
  if (!file.raw) return
  const isImage = file.raw.type.startsWith('image/')
  const isLt10M = file.raw.size / 1024 / 1024 < 10

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('图片大小不能超过 10MB!')
    return false
  }
  const loader = ElLoading.service({ text: '上传图片中...' })
  try {
    const base64 = await convertToBase64(file.raw)
    faceImgBase64List.value.push(base64)
    ElMessage.success("上传成功")
  } catch (error) {
    ElMessage.error('图片上传失败')
  } finally {
    loader.close()
  }
}

const handleImageRemove = (file: any) => {
  const index = sampleForm.images?.indexOf(file.raw)
  if (index !== undefined && index > -1) {
    faceImgBase64List.value.splice(index, 1)
  }
}

// 修改字段添加方法
const addSampleField = (type: 'extend' | 'face') => {
  const newField = { key: '', value: '' }
  if (type === 'extend') {
    if (!sampleForm.sampleData) {
      sampleForm.sampleData = []
    }
    newField.key = 'name'
    sampleForm.sampleData.push(newField)
  } else {
    newField.key = 'label'
    faceForm.faceData.push(newField)
  }
}

// 修改字段删除方法
const removeSampleField = (type: 'extend' | 'face', index: number) => {
  if (type === 'extend') {
    if (!sampleForm.sampleData) {
      return
    }
    sampleForm.sampleData.splice(index, 1)
  } else {
    faceForm.faceData.splice(index,1)
  }
}

// 修改表单提交方法
const submitSampleForm = async () => {
  try {
    await sampleFormRef.value?.validate()
    // 创建样本
    ElMessage.info("正在创建样本")
    const response = await sampleApi.create(sampleForm)
    if (response.data?.code !== 0) {
      ElMessage.error("创建失败：" + response.data?.message)
      return
    }
    // 创建人脸
    createFace()
  } catch (error) {
    console.error('创建样本失败:', error)
  }
}

// 创建人脸
const createFace = () => {
  for (const base64File of faceImgBase64List.value) {
    faceForm.imageBase64 = base64File
    const response = faceApi.create(faceForm)
    // if (response.data?.code !== 0) {
    //   ElMessage.error("创建人脸失败：" + response.data?.message)
    //   return
    // }
  }
  ElMessage.success("创建人脸成功")
  showSampleDialog.value = false
  // 清空所有相关数据
  faceImgBase64List.value = []
  faceForm.faceData = []
  faceForm.faceScoreThreshold = 0
  faceForm.maxConfidenceThresholdWithOtherSample = 0
  faceForm.minConfidenceThresholdWithThisSample = 0
}

// 删除样本
const deleteSample = async (row: SampleDataRepVo) => {
  try {
    await ElMessageBox.confirm(`确认删除样本 "${row.sampleId}"?`, '警告', {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
      confirmButtonClass: 'el-button--danger'
    })
    console.log("删除ß")
    const res = await sampleApi.delete({
      namespace: namespace.value,
      collectionName: sampleQuery.collectionName,
      sampleId: row.sampleId
    })
    console.log(res)
    ElMessage.success('删除成功')
    await loadSamples()
  } catch (error) {
    console.log('取消删除')
  }
}

// UI控制
const showCollectForm = () => {
  collectForm.collectionName = ''
  collectForm.sampleColumns = []
  showCollectDialog.value = true
}

const showSampleForm = () => {
  // 如果有集合，默认选择第一个
  if (collections.value.length > 0) {
    sampleForm.collectionName = collections.value[0].collectionName
  }
  sampleForm.sampleId = generateSampleId()
  sampleForm.sampleData = []
  faceImgBase64List.value = []
  faceForm.faceData = []
  faceForm.sampleId = sampleForm.sampleId
  faceForm.collectionName = sampleForm.collectionName
  faceForm.faceScoreThreshold = 0
  faceForm.maxConfidenceThresholdWithOtherSample = 0
  faceForm.minConfidenceThresholdWithThisSample = 0
  // 清空上传组件
  uploadRef.value?.clearFiles()
  showSampleDialog.value = true
}

// 修改阈值相关的格式化函数
const formatTooltip = (value: number): string => {
  return `${value}%`
}

// 获取指定字段值的辅助函数
const getFieldValue = (sampleData: Array<{ key: string; value: string }>, fieldName: string): string => {
  const field = sampleData?.find(item => item.key === fieldName)
  return field?.value || '-'
}

// 获取人脸标签的辅助函数
const getFaceLabels = (sampleData: Array<{ key: string; value: string }>) => {
  return sampleData?.filter(item => item.key.startsWith('label')) || []
}

// 处理每页显示数量变化
const handleSizeChange = (val: number) => {
  pagination.size = val
  pagination.current = 1
  loadSamples()
}

// 处理页码变化
const handleCurrentChange = (val: number) => {
  pagination.current = val
  loadSamples()
}

// 处理集合管理每页显示数量变化
const handleCollectSizeChange = (val: number) => {
  collectPagination.size = val
  collectPagination.current = 1
  loadCollections()
}

// 处理集合管理页码变化
const handleCollectCurrentChange = (val: number) => {
  collectPagination.current = val
  loadCollections()
}

// 新增人脸弹窗
const showAddFaceDialog = ref(false)
const addFaceFormRef = ref<FormInstance>()
const addFaceForm = reactive<FaceDataReq>({
  collectionName: '',
  namespace: '',
  sampleId: '',
  faceData: [],
  faceScoreThreshold: 0,
  imageBase64: '',
  maxConfidenceThresholdWithOtherSample: 0,
  minConfidenceThresholdWithThisSample: 0
})
const addFaceImgBase64List = ref<string[]>([])

// 显示新增人脸弹窗
const openAddFaceDialog = (row: SampleDataRepVo) => {
  addFaceForm.collectionName = sampleQuery.collectionName
  addFaceForm.namespace = namespace.value
  addFaceForm.sampleId = row.sampleId
  addFaceForm.faceData = []
  addFaceForm.faceScoreThreshold = 0
  addFaceForm.maxConfidenceThresholdWithOtherSample = 0
  addFaceForm.minConfidenceThresholdWithThisSample = 0
  addFaceImgBase64List.value = []
  // 清空上传组件
  addFaceUploadRef.value?.clearFiles()
  showAddFaceDialog.value = true
}

// 处理新增人脸图片变化
const handleAddFaceImageChange = async (file: any) => {
  if (!file.raw) return
  const isImage = file.raw.type.startsWith('image/')
  const isLt10M = file.raw.size / 1024 / 1024 < 10

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('图片大小不能超过 10MB!')
    return false
  }
  const loader = ElLoading.service({ text: '上传图片中...' })
  try {
    const base64 = await convertToBase64(file.raw)
    addFaceImgBase64List.value.push(base64)
    ElMessage.success("上传成功")
  } catch (error) {
    ElMessage.error('图片上传失败')
  } finally {
    loader.close()
  }
}

// 处理新增人脸图片移除
const handleAddFaceImageRemove = (file: any) => {
  const index = addFaceImgBase64List.value.indexOf(file.raw)
  if (index > -1) {
    addFaceImgBase64List.value.splice(index, 1)
  }
}

// 提交新增人脸表单
const submitAddFaceForm = () => {
  try {
    addFaceFormRef.value?.validate()
    ElMessage.info("正在创建人脸")

    for (const base64File of addFaceImgBase64List.value) {
      addFaceForm.imageBase64 = base64File
      const res = faceApi.create(addFaceForm)
      // if (res.data?.code !== 0) {
      //   ElMessage.error("创建人脸失败：" + res.data?.message)
      //   return
      // }
    }

    ElMessage.success("创建人脸成功")
    showAddFaceDialog.value = false
    // 清空所有相关数据
    addFaceImgBase64List.value = []
    addFaceForm.faceData = []
    addFaceForm.faceScoreThreshold = 0
    addFaceForm.maxConfidenceThresholdWithOtherSample = 0
    addFaceForm.minConfidenceThresholdWithThisSample = 0
    loadSamples()
  } catch (error) {
    console.error('创建人脸失败！:', error)
  }
}

// 添加人脸字段
const addFaceField = () => {
  addFaceForm.faceData.push({ key: '', value: '' })
}

// 移除人脸字段
const removeFaceField = (index: number) => {
  addFaceForm.faceData.splice(index, 1)
}

// 添加 ref
const uploadRef = ref()
const addFaceUploadRef = ref()
</script>

<style lang="scss" scoped>
.red-management {
  height: calc(100vh - 130px);
  --primary-color: #ff4d4f;
  --secondary-color: #ff5252;
  --accent-color: #ff8a80;
  --bg-color: #f8f9fa;
  --card-bg: #ffffff;
  --text-primary: #2c3e50;
  --text-secondary: #666;
  --border-color: #ffe0e0;

  .top-layout {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px 32px 0 32px;

    .section-title-container {
      color: #ff4d4f;
      flex: 1;
    }

    .collection-selector {
      flex: 2;
      padding: 0 20px;

      .collection-select {
        width: 100%;

        :deep(.el-input__wrapper) {
          background-color: var(--detail-section-background);
          border-radius: 20px;
          box-shadow: none;
          border: 1px solid var(--border-color);
          transition: all 0.3s;

          &:hover {
            border-color: var(--primary-color);
          }

          &.is-focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 1px var(--primary-color);
          }

          .el-input__inner {
            font-size: 14px;
            color: #333;
          }

          .el-select__caret {
            color: #999;
            transition: all 0.3s;

            &.is-reverse {
              transform: rotateZ(180deg);
            }
          }
        }

        .el-icon {
          color: var(--primary-color);
          font-size: 18px;
        }
      }
    }

    .right-buttons {
      margin-left: 20px;
      flex: 1;
      display: flex;
      justify-content: flex-end;
      gap: 20px;
    }
  }

  .button-container {
    display: flex;


    .active-button {
      color: white;
      background: linear-gradient(
          45deg,
          var(--primary-color),
          var(--secondary-color)
      );
    }
  }

  .management-main {
    display: flex;
    height: calc(100vh - 130px);
    padding: 20px 32px;

    .collect-section,
    .sample-section {
      flex: 1;
      background: var(--el-bg-color);
      border-radius: 8px;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
      display: flex;
      flex-direction: column;
      transition: all 0.3s;

      .data-table {
        flex: 1;
        border-radius: 8px;
        overflow: hidden;

        :deep(.el-table) {
          --el-table-border-color: var(--el-border-color-lighter);
          --el-table-header-bg-color: var(--el-fill-color-light);
          --el-table-row-hover-bg-color: var(--el-color-danger-light-9);
          --el-table-current-row-bg-color: var(--el-color-danger-light-9);
          --el-table-header-text-color: var(--el-color-danger);
          --el-table-text-color: var(--el-text-color-regular);

          background-color: transparent;
          border: none;

          .el-table__header-wrapper {
            th {
              background-color: var(--el-fill-color-light);
              color: var(--el-color-danger);
              font-weight: 600;
              padding: 16px 0;
              border-bottom: 1px solid var(--el-border-color-lighter);
            }
          }

          .el-table__body-wrapper {
            td {
              padding: 16px 0;
              border-bottom: 1px solid var(--el-border-color-lighter);
            }
          }

          .el-table__row {
            transition: all 0.3s;

            &:hover {
              background-color: var(--el-color-danger-light-9) !important;
            }
          }
        }

        .field-tags {
          display: flex;
          flex-wrap: wrap;
          gap: 6px;

          .field-tag {
            border-color: var(--el-color-danger-light-5);
            color: var(--el-color-danger);
            background: var(--el-color-danger-light-9);
            transition: all 0.3s;

            &:hover {
              border-color: var(--el-color-danger);
              background: var(--el-color-danger-light-8);
            }
          }
        }

        .label-tags {
          display: flex;
          flex-wrap: wrap;
          gap: 6px;

          .label-tag {
            border-color: var(--el-border-color-lighter);
            color: var(--el-text-color-regular);
            background: var(--el-fill-color-light);
            transition: all 0.3s;

            &:hover {
              border-color: var(--el-color-primary);
              color: var(--el-color-primary);
              background: var(--el-color-primary-light-9);
            }
          }
        }
      }

      .pagination-wrapper {
        padding: 16px 24px;
        display: flex;
        justify-content: flex-end;
        border-top: 1px solid var(--el-border-color-lighter);
        background-color: var(--el-bg-color);

        :deep(.el-pagination) {
          --el-pagination-button-color: var(--el-text-color-regular);
          --el-pagination-hover-color: var(--el-color-danger);
          --el-pagination-active-color: var(--el-color-danger);

          .el-pagination__total {
            margin-right: 16px;
            color: var(--el-text-color-regular);
          }

          .el-pagination__sizes {
            margin-right: 16px;
          }

          .el-pagination__jump {
            margin-left: 16px;
          }

          .el-pagination__total,
          .el-pagination__sizes,
          .el-pagination__jump {
            .el-input__wrapper {
              background-color: var(--el-fill-color-light);
              border: 1px solid var(--el-border-color-lighter);
              border-radius: 4px;
              box-shadow: none;

              &:hover {
                border-color: var(--el-color-danger);
              }

              &.is-focus {
                border-color: var(--el-color-danger);
                box-shadow: 0 0 0 1px var(--el-color-danger-light-3);
              }
            }
          }

          .btn-prev,
          .btn-next {
            background-color: var(--el-fill-color-light);
            border: 1px solid var(--el-border-color-lighter);
            border-radius: 4px;
            margin: 0 4px;

            &:hover {
              color: var(--el-color-danger);
              border-color: var(--el-color-danger);
            }

            &.is-disabled {
              background-color: var(--el-fill-color-lighter);
              border-color: var(--el-border-color-lighter);
              color: var(--el-text-color-disabled);
            }
          }

          .el-pager {
            li {
              background-color: var(--el-fill-color-light);
              border: 1px solid var(--el-border-color-lighter);
              border-radius: 4px;
              margin: 0 4px;

              &:hover {
                color: var(--el-color-danger);
                border-color: var(--el-color-danger);
              }

              &.active {
                background-color: var(--el-color-danger);
                color: white;
                border-color: var(--el-color-danger);
              }
            }
          }
        }
      }
    }
  }

  // 弹窗样式覆盖
  :deep(.collect-dialog),
  :deep(.sample-dialog) {
    .el-dialog__header {
      border-bottom: 1px solid var(--el-border-color-lighter);
      margin-right: 0;
      padding: 20px 24px;
    }

    .el-dialog__title {
      color: var(--el-color-danger);
      font-weight: 600;
      font-size: 18px;
    }

    .el-dialog__body {
      padding: 24px;
    }

    .el-dialog__footer {
      border-top: 1px solid var(--el-border-color-lighter);
      padding: 16px 24px;
    }

    .el-form {
      .el-form-item {
        margin-bottom: 24px;

        .el-form-item__label {
          font-weight: 500;
          color: var(--el-text-color-primary);
        }

        .el-input__wrapper,
        .el-textarea__wrapper {
          box-shadow: none;
          border: 1px solid var(--el-border-color);
          transition: all 0.3s;

          &:hover {
            border-color: var(--el-color-danger);
          }

          &.is-focus {
            border-color: var(--el-color-danger);
            box-shadow: 0 0 0 1px var(--el-color-danger-light-3);
          }
        }
      }
    }

    .field-config {
      background: var(--el-fill-color-light);
      border-radius: 8px;
      padding: 20px;
      margin-bottom: 24px;

      .field-group {
        .field-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 20px;
          padding-bottom: 12px;
          border-bottom: 1px solid var(--el-border-color-lighter);

          h4 {
            color: var(--el-color-danger);
            margin: 0;
            font-size: 16px;
            font-weight: 600;
          }

          .el-button {
            border-color: var(--el-color-danger);
            color: var(--el-color-danger);

            &:hover {
              background-color: var(--el-color-danger-light-9);
            }
          }
        }

        .field-item {
          display: flex;
          gap: 12px;
          margin-bottom: 16px;
          padding: 12px;
          background: var(--el-bg-color);
          border-radius: 6px;
          transition: all 0.3s;

          &:hover {
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
          }

          .field-name {
            width: 160px;
          }

          .field-type {
            width: 140px;
          }

          .field-desc {
            flex: 1;
          }

          .el-button {
            padding: 8px;
            color: var(--el-color-danger);

            &:hover {
              background-color: var(--el-color-danger-light-9);
            }
          }
        }
      }
    }

    .el-switch {
      --el-switch-on-color: var(--el-color-danger);
    }
  }

  .sample-dialog {
    .field-section {
      border: 1px solid var(--border-color);
      border-radius: 8px;
      padding: 16px;
      margin-bottom: 24px;

      .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;

        h4 {
          color: var(--primary-color);
          margin: 0;
          font-size: 15px;
        }
      }

      .field-item {
        display: flex;
        gap: 10px;
        margin-bottom: 12px;

        .field-name {
          width: 140px;
        }

        .field-value {
          flex: 1;
        }
      }
    }

    .form-tip {
      font-size: 12px;
      color: #666;
      margin-top: 4px;
    }

    .upload-tip {
      font-size: 12px;
      color: #666;
      line-height: 1.5;
    }

    .slider-container {
      position: relative;
      padding: 16px 24px;
      background: var(--el-bg-color);
      border-radius: 8px;
      border: 1px solid var(--el-border-color-lighter);
      margin-top: 8px;
      transition: all 0.3s;

      :deep(.el-slider) {
        --el-slider-button-size: 20px;
        --el-slider-height: 8px;
        margin: 8px 0;

        .el-slider__runway {
          background-color: var(--el-fill-color-light);
          height: var(--el-slider-height);
          margin: 16px 0;
        }

        .el-slider__bar {
          background: linear-gradient(90deg, var(--el-color-danger), var(--el-color-danger-light-3));
          height: var(--el-slider-height);
        }

        .el-slider__button-wrapper {
          top: -6px;
          width: var(--el-slider-button-size);
          height: var(--el-slider-button-size);
        }

        .el-slider__button {
          width: var(--el-slider-button-size);
          height: var(--el-slider-button-size);
          border: 2px solid var(--el-color-danger);
          background-color: var(--el-bg-color);
          transition: transform 0.2s ease;

          &:hover {
            transform: scale(1.1);
          }
        }

        .el-slider__input {
          width: 60px;
          margin-left: 20px;

          .el-input__wrapper {
            padding: 0;
            box-shadow: none;
            border: 1px solid var(--el-border-color-lighter);
            background-color: var(--el-fill-color-light);

            &:hover {
              border-color: var(--el-color-danger);
            }

            &.is-focus {
              border-color: var(--el-color-danger);
              box-shadow: 0 0 0 1px var(--el-color-danger-light-3);
            }
          }

          .el-input__inner {
            height: 28px;
            font-size: 14px;
            text-align: center;
            color: var(--el-color-danger);
            font-weight: 500;
            padding: 0 8px;
          }

          .el-input-number__decrease,
          .el-input-number__increase {
            display: none;
          }
        }
      }

      .slider-tip {
        font-size: 13px;
        color: var(--el-text-color-regular);
        margin-top: 12px;
        line-height: 1.6;
        padding: 8px 12px;
        background: var(--el-color-danger-light-9);
        border-radius: 4px;
        border-left: 3px solid var(--el-color-danger);
      }
    }
  }

  .label-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;

    .label-tag {
      border-color: var(--accent-color);
      color: var(--primary-color);
      background: #ffebee;
    }
  }
}
</style>
